from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
import os
from datetime import datetime, timedelta

app = FastAPI()

# 配置图片目录
PHOTO_DIR = os.path.join(os.getcwd(), 'scratchphoto')
app.mount("/static", StaticFiles(directory=PHOTO_DIR), name="static")

@app.get("/")
async def index():
    return {"Hello":"How are you"}

@app.get("/scratchphoto/{id}")
# 异步函数，用于返回指定id的图片
async def serve_photo(id: str):
    try:
        # 拼接文件名
        filename = f"{id}.png"
        # 拼接文件路径
        file_path = os.path.join(PHOTO_DIR, filename)
        
        # 如果文件不存在，则使用默认图片
        if not os.path.exists(file_path):
            filename = "scratch.png"
        
        # 返回文件响应
        response = FileResponse(
            os.path.join(PHOTO_DIR, filename),
            headers={
                "Cache-Control": "public, max-age=1209600",
                "Expires": (datetime.now() + timedelta(seconds=1209600)).strftime('%a, %d %b %Y %H:%M:%S GMT')
            }
        )
        return response
    except Exception as e:
        # 抛出HTTP异常
        raise HTTPException(status_code=500, detail=f"Server Error: {e}")


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=5218)

